#-*- coding: utf-8 -*-
from rdflib import Graph
from io import StringIO
from rdflib.term import URIRef
from util.Location import Location
from util.Metadata import Metadata

vcard_url = 'http://www.w3.org/2006/vcard/ns#'
dcterms_url = 'http://purl.org/dc/terms/'
foaf_url = 'http://xmlns.com/foaf/spec/index.rdf'
cs_url = 'http://cs.unibo.it/ontology/'
xsd_url = 'http://www.w3.org/2001/XMLSchema#'

location = {
            'tel' : URIRef(vcard_url + 'tel'),
            'note' : URIRef(vcard_url + 'note'),
            'address' : URIRef(vcard_url + 'extended-address'),
            'lat' : URIRef(vcard_url + 'latitude'),
            'long' : URIRef(vcard_url + 'longitude'),
            'fax' : URIRef(vcard_url + 'fax'),
            'category' : URIRef(vcard_url + 'category'),
            'subcategory' : URIRef(vcard_url + 'subcategory'),
            'name' :  URIRef(vcard_url + 'fn'),
            'opening' :  URIRef(cs_url + 'opening'),
            'closing' :  URIRef(cs_url + 'closing')
          }

metadata = {
             'valid' : URIRef(dcterms_url + 'valid'),
             'source' : URIRef(dcterms_url + 'source'),
             'creator' : URIRef(dcterms_url + 'creator'),
             'created' : URIRef(dcterms_url + 'created'),
             'version' : URIRef(dcterms_url + 'description')}

def parse_ttl(ttl_str):
    turtle = Graph()
    
    if type(ttl_str) != unicode:
        ttl_str = unicode(ttl_str,'utf8')

    src = turtle.parse(StringIO(ttl_str), format='n3')
    
    locations_dict = {}
    meta = Metadata()
    
    for s in src.subjects():
        if src.value(s, location['address']):
            loc = Location()
            loc.id = str(s[s.rfind('/')+1:])
            loc.address = str(src.value(s, location['address']))
            loc.category = str(src.value(s, location['category']))
            loc.closing = str(src.value(s, location['closing']))
            loc.opening = str(src.value(s, location['opening']))
            loc.lat = float(src.value(s, location['lat']))
            loc.long = float(src.value(s, location['long']))
            loc.name = str(src.value(s, location['name']))
            loc.metadata = meta
        
            tel = src.value(s, location['tel'])
            if tel:
                loc.tel = tel
             
            note = src.value(s, location['note'])   
            if note:
                loc.note = note
            
            subcat = src.value(s, location['subcategory'])
            if subcat:
                loc.subcategory = subcat
            
            locations_dict[loc.id] = loc
        elif src.value(s, metadata['creator']):
            meta.valid =  src.value(s, metadata['valid'])
            meta.source = src.value(s, metadata['source'])
            meta.creator = src.value(s, metadata['creator'])
            meta.created = src.value(s, metadata['created'])
            meta.version = src.value(s, metadata['version'])
    
    return locations_dict


def write_ttl(locations_dict):
    ttl = '@prefix vcard: <http://www.w3.org/2006/vcard/ns#> .\n'
    ttl += '@prefix cs: <http://cs.unibo.it/ontology/> .\n'
    ttl += '@prefix dcterms: <http://purl.org/dc/terms/> .\n'
    ttl += '@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n'
    ttl += '@prefix this: <http://bella.punto> .\n'
    ttl += '@prefix : <http://www.essepuntato.it/resource/> .\n'
    
    write_meta = True
    
    for k in locations_dict.keys():
        loc = locations_dict[k]
        if write_meta:
            metadata = loc.metadata
            ttl += '\nthis:metadata\n'
            ttl += '\tdcterms:creator "%s"\n' % metadata.creator
            ttl += '\t;dcterms:created "%s"^^xsd:date\n' % metadata.created
            ttl += '\t;dcterms:description "%s"\n' % metadata.version
            ttl += '\t;dcterms:valid "%s"^^xsd:date\n' % metadata.valid
            ttl += '\t;dcterms:source "%s".\n' % metadata.source
            ttl += '\n'
            write_meta = False
        
        ttl += ':%s\n' % loc.id
        ttl += '\t vcard:category "%s"\n' % loc.category
        ttl += '\t; vcard:fn "%s"\n' % loc.name.replace('"','\\"')
        ttl += '\t; vcard:extended-address "%s"\n' % loc.address
        ttl += '\t; vcard:latitude "%s"\n' % loc.lat
        ttl += '\t; vcard:longitude "%s"\n' % loc.long
        
        if loc.tel:
            ttl += '\t; vcard:tel "%s"\n' % loc.tel
        
        if loc.subcategory:
            ttl += '\t; vcard:subcategory "%s"\n' % loc.subcategory
        
        if loc.note:
            ttl += '\t; vcard:note "%s"\n' % loc.note
            
        ttl += '\t; vcard:category "%s"\n' % loc.category
        ttl += '\t; cs:opening "%s"\n' % loc.opening
        ttl += '\t; cs:closing "%s" .\n' % loc.closing
        ttl += '\n'
        
    if type(ttl) == str:
        ttl = unicode(ttl,'utf8')
            
    return ttl